using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using TST.SharePoint.Shared;
using System.Xml;
using System.Collections;
using TST.SharePointObjects.ContentWebParts.Shared.WebControls;

namespace TST.SharePointObjects.ContentWebParts
{
    public class FieldsConfiguration: ConfigurationControl
    {
        protected Label labelSelectFields;
        protected SortListBox selectFields;
        protected Table tableSelectFields;
        protected Button buttonAddField;
        protected Button buttonRemove;
        protected ListBox selectedFields;
        protected Label labelDisplayOption;
        protected Label labelFieldOptions;
        protected Label labelDisplayname;
        protected TextBox editDisplayname;
        protected Label labelLinkField;
        protected SortDropDownList selectLinkField;
        protected Label labelNewWindow;
        protected CheckBox cbkNewWindow;
        protected LinkButton buttonSaveField;
        protected ImageButton buttonSaveFieldImg;
        protected ImageButton buttonMoveUpImg;
        protected LinkButton buttonMoveUp;
        protected ImageButton buttonMoveDownImg;
        protected LinkButton buttonMoveDown;
        protected Label labelSelected;
        protected Label labelAvailable;
        protected TableCell cellInfo;
        private LiteralControl _info;
        protected TableRow rowFieldOptions;
        protected TableRow rowFields;
        protected TableRow rowButtons;
        protected TableRow rowDisplayname;
        protected TableRow rowLinkField;
        protected TableRow rowNewWindow;

        public void WriteConfiguration(bool setFieldRefSettings)
        {
            if (CurrentConfiguration == null || Datasource == null)
            {
                return;
            }

            // Reset the current configuration on the webpart.
            CurrentConfiguration.Fields.Clear();
            foreach (ListItem item in selectedFields.Items)
            {
                if (EditConfiguration.Fields.Contains(item.Value))
                {
                    CurrentConfiguration.Fields.Add(EditConfiguration.Fields[item.Value]);
                }
            }
        }

        public void ReadConfiguration()
        {
            if (CurrentConfiguration == null || Datasource == null)
            {
                return;
            }

            // Check if the configuration holds field references.
            if (CurrentConfiguration.Fields.Count > 0)
            {
                // Update our local configuration (stored in the viewstate while editting).
                foreach (FieldReference reference in CurrentConfiguration.Fields)
                {
                    EditConfiguration.Fields.Add(reference);
                }
            }
            AddDataSourceFields();
        }

        private void AddDataSourceFields()
        {
            // Reset the listbox with items to select.
            selectFields.Items.Clear();
            selectedFields.Items.Clear();

            selectLinkField.Items.Clear();
            ListItem emptyLinkField = new ListItem(string.Format("-- {0} --", TST.SharePointObjects.ContentWebParts.TST_SharePointObjects_ContentWebParts.PleaseSelectAField), Guid.Empty.ToString("B"));

            selectLinkField.Items.Add(emptyLinkField);
            foreach (FieldReference fieldRef in EditConfiguration.Fields)
            {
                if (Datasource.Fields.Contains(fieldRef.Id))
                {
                    Field field = Datasource.Fields[fieldRef.Id];
                    ListItem item = new ListItem(field.DisplayName, field.Name);
                    selectedFields.Items.Add(item);
                }
            }

            // Iterate through all fields in the datasource.
            if (Datasource.Fields.Count > 0)
            {
                foreach (Field field in Datasource.Fields)
                {
                    // Generate a new listitem object. Add to fields to be 
                    // selected (if it is not yet selected).
                    ListItem item = new ListItem(field.DisplayName, field.Name);
                    if (!EditConfiguration.Fields.Contains(field.Name))
                        selectFields.Items.Add(item);

                    if (field.FieldType == FieldType.Url)
                    {
                        ListItem linkItem = new ListItem(field.DisplayName, field.Name);
                        selectLinkField.Items.Add(linkItem);
                    }
                }
            }
        }

        private void InitUI()
        {
            rowFieldOptions.Enabled = Datasource.Fields.Count>0;
            rowFields.Enabled = Datasource.Fields.Count > 0;
            rowButtons.Enabled = (!string.IsNullOrEmpty(selectedFields.SelectedValue));
            rowDisplayname.Enabled = (!string.IsNullOrEmpty(selectedFields.SelectedValue));
            rowLinkField.Enabled = (!string.IsNullOrEmpty(selectedFields.SelectedValue));
            rowNewWindow.Enabled = (!string.IsNullOrEmpty(selectedFields.SelectedValue));
            cellInfo.Enabled = true;
        }

        public void Clear()
        {
            if (Datasource != null)
            {
                Datasource.ClearFields();
                if (Datasource.Configuration != null)
                    Datasource.Configuration.Fields.Clear();
            }
            if (EditConfiguration != null)
            {
                EditConfiguration.Fields.Clear();
            }
            AddDataSourceFields();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            _info = new LiteralControl(string.Format("<a href=\"http://www.tonstegeman.com/cbt\" target=\"_blank\"><img border=\"0\" src=\"/_layouts/images/HELPICON.GIF\"/>More information</a>"));
            cellInfo.Controls.Add(_info);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            InitUI();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            buttonAddField.Click += new EventHandler(buttonAddField_Click);
            buttonRemove.Click += new EventHandler(buttonRemove_Click);
            selectedFields.SelectedIndexChanged += new EventHandler(selectedFields_SelectedIndexChanged);
            buttonSaveField.Click += new EventHandler(buttonSaveField_Click);
            buttonSaveFieldImg.Click += new ImageClickEventHandler(buttonSaveFieldImg_Click);
            buttonMoveDown.Click += new EventHandler(buttonMoveDown_Click);
            buttonMoveDownImg.Click += new ImageClickEventHandler(buttonMoveDownImg_Click);
            buttonMoveUp.Click += new EventHandler(buttonMoveUp_Click);
            buttonMoveUpImg.Click += new ImageClickEventHandler(buttonMoveUpImg_Click);
        }

        void buttonMoveUpImg_Click(object sender, ImageClickEventArgs e)
        {
            Move(true);
        }

        void buttonMoveUp_Click(object sender, EventArgs e)
        {
            Move(true);
        }

        void buttonMoveDownImg_Click(object sender, ImageClickEventArgs e)
        {
            Move(false);
        }

        private void Move(bool moveUp)
        {
            if (!string.IsNullOrEmpty(selectedFields.SelectedValue))
            {
                int index = selectedFields.SelectedIndex;
                ListItem item = new ListItem(selectedFields.SelectedItem.Text, selectedFields.SelectedValue);
                selectedFields.Items.RemoveAt(index);
                int newIndex;
                if (moveUp)
                    newIndex = (index > 0) ? index - 1 : selectedFields.Items.Count;
                else
                    newIndex = (index < selectedFields.Items.Count) ? index + 1 : 0;
                selectedFields.Items.Insert(newIndex, item);
                item.Selected = true;
            }
        }

        void buttonMoveDown_Click(object sender, EventArgs e)
        {
            Move(false);
        }

        void buttonSaveFieldImg_Click(object sender, ImageClickEventArgs e)
        {
            SaveField();
        }

        void buttonSaveField_Click(object sender, EventArgs e)
        {
            SaveField();
        }

        private void SaveField()
        {
            FieldReference currentField = EditConfiguration.Fields[selectedFields.SelectedValue];
            if (currentField != null)
            {
                currentField.LinkFieldId = selectLinkField.SelectedValue;
                currentField.DisplayName = editDisplayname.Text;
                currentField.OpenInNewWindow = cbkNewWindow.Checked;
            }
        }

        private void selectedFields_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Initialize empty values.
            selectLinkField.SelectedValue = Guid.Empty.ToString("B");
            editDisplayname.Text = string.Empty;
            cbkNewWindow.Checked = false;

            // Get values for the selected field reference.
            FieldReference currentField = EditConfiguration.Fields[selectedFields.SelectedValue];
            if (currentField != null)
            {
                if (Field.IsFieldId(currentField.LinkFieldId))
                {
                    selectLinkField.SelectedValue = currentField.LinkFieldId;
                    if (string.IsNullOrEmpty(currentField.DisplayName))
                        editDisplayname.Text = Datasource.Fields[selectedFields.SelectedValue].DisplayName;
                    else
                        editDisplayname.Text = currentField.DisplayName;
                    cbkNewWindow.Checked = currentField.OpenInNewWindow;
                }
            }
        }

        void buttonRemove_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(selectedFields.SelectedValue))// && Datasource.Fields.Contains(_selectFields.SelectedValue))
            {
                List<string> itemsToDelete = new List<string>();
                foreach (ListItem item in selectedFields.Items)
                {
                    if (item.Selected)
                    {
                        itemsToDelete.Add(item.Value);
                    }
                }
                foreach (string itemToDelete in itemsToDelete)
                {
                    if (EditConfiguration.Fields.Contains(itemToDelete))
                    {
                        EditConfiguration.Fields.Remove(itemToDelete);
                    }
                }
                AddDataSourceFields();

                selectedFields.SelectedIndex = -1;
            }
        }

        private void buttonAddField_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(selectFields.SelectedValue))
            {
                foreach (ListItem item in selectFields.Items)
                {
                    if (item.Selected)
                    {
                        FieldReference newRef = new FieldReference(Datasource.Fields[item.Value]);
                        EditConfiguration.Fields.Add(newRef);
                    }
                }
                AddDataSourceFields();

                // Reset the list box to have no item selected.
                selectFields.SelectedIndex = -1;
            }
        }

    }
}
